import os.path
from typing import Any

import yaml
from pydantic import BaseModel
from pydantic import Field

from internal.lib import pydantic_moudle
from .tools_bean import ToolsModel


class ProviderItem(BaseModel):
    name: str
    label: str
    description: str
    background: str
    category: str
    icon: str


class Provider(BaseModel):
    name: str
    position: int
    provider_item: ProviderItem
    provider_tool_bean: dict[str, ToolsModel] = Field(default_factory=dict)
    provider_tool_fun: dict[str, Any] = Field(default_factory=dict)

    def __init__(self, **data: Any):
        super().__init__(**data)
        self._init_provider()

    def get_tool_bean(self, tool_name: str) -> ToolsModel:
        return self.provider_tool_bean.get(tool_name)

    def get_tool_all(self) -> list[ToolsModel]:
        return [item for item in self.provider_tool_bean.values()]

    def get_tool_fun(self, tool_name: str) -> Any:
        return self.provider_tool_fun.get(tool_name)

    def _init_provider(self):
        print(self.name)
        path = os.path.abspath(__file__)
        dir_name = os.path.dirname(path)
        parent_join = os.path.join(os.path.dirname(dir_name), "providers", self.name, "position.yaml")
        with open(parent_join, encoding="utf-8") as f:
            google_tools_arr = yaml.safe_load(f)
            for tool_name in google_tools_arr:
                google_serper_yaml_path = os.path.join(os.path.dirname(dir_name), "providers", self.name,
                                                       f"{tool_name}.yaml")

                with open(google_serper_yaml_path, encoding="utf-8") as j:
                    google_serper = yaml.safe_load(j)
                    self.provider_tool_bean[tool_name] = ToolsModel(**google_serper)
                    self.provider_tool_fun[tool_name] = pydantic_moudle(
                        f"internal.core.tools.providers.{self.name}",
                        tool_name
                    )
